#!/usr/bin/python -u
# -*- coding: utf-8 -*-

#import lxml
#from lxml import etree
import libxml2
#import time
import traceback
import sys
import re
import logging
import time
import random

from pyxmpp.all import JID,Iq,Presence,Message,StreamError
from protocol.iq_sit_down import iq_sit_down,iq_get_all_scene_users,iq_get_scene_users
#from pyxmpp.jabber.all import Client
#from pyxmpp.jabber.client import JabberClient

from simpleclient import SimpleClient 
from libxml2 import xmlNode
from logic import thread_msgs

class Disconnected(Exception):
    pass

class MyClient(SimpleClient):    
    def __init__(self,jid=None,password=None,server=None,port=5222,deviceid=None,lat=0.0,lng=0.0,
            auth_methods=("sasl:DIGEST-MD5",),
            tls_settings=None,keepalive=0):
        SimpleClient.__init__(self,
                    jid = jid,
                    password = password,
                    server = server,
                    port = port,
                    deviceid = deviceid,                                        
                    lat=lat,
                    lng=lng,
                    auth_methods = auth_methods,
                    tls_settings = tls_settings,
                    keepalive = keepalive)
        self.__logger=logging.getLogger("pyxmpp.SimpleClient")        
        self.thread = None
        self.sceneid = None
        self.logon_ui = None
        self.logic_ui = None
        self.chat_ui = None        
        self.lasttime = time.time()
            
    def session_started(self):    
        self.jid
        self.stream.send(Presence())
        if (self.logon_ui):
            self.logon_ui.logic_logon_success()
        if (self.logic_ui):
            self.logic_ui.show(self)
        ##self.get_all_scene_user_list()
        pattern = re.compile(r"(?P<prefix>.*)_(?P<count>\d+)")
        deviceidstr = self.deviceid
        deviceidmatch = pattern.match(deviceidstr)
        
        count = 0
        if (deviceidmatch):                            
            scount = deviceidmatch.group("count")
            count = int(scount)
                
        self.scene = 0 
        self.desk = 0
            
        
        whilecount = self.thread.desknolist.__len__()+1
        while(whilecount>0):
            tmpdesk = random.choice(self.thread.desknolist)
            if (count%2==0):
                if (self.thread.desknostate[tmpdesk]==0 or self.thread.desknostate[tmpdesk]==2):
                    self.desk = tmpdesk
                    self.scene = self.thread.desknomap[tmpdesk]
                    if (self.thread.desknostate[tmpdesk]==0):
                        self.thread.desknostate[tmpdesk]=1
                    elif (self.thread.desknostate[tmpdesk]==2):
                        self.thread.desknostate[tmpdesk]=3
                    break
            else:
                if (self.thread.desknostate[tmpdesk]==1 or self.thread.desknostate[tmpdesk]==0):
                    self.desk = tmpdesk
                    self.scene = self.thread.desknomap[tmpdesk]
                    if (self.thread.desknostate[tmpdesk]==0):
                        self.thread.desknostate[tmpdesk]=2
                    elif (self.thread.desknostate[tmpdesk]==1):
                        self.thread.desknostate[tmpdesk]=3
                    break  
            --whilecount   
            
        if (0==self.desk):
            for tmpdesk in self.thread.desknolist:
                if (count%2==0):
                    if (self.thread.desknostate[tmpdesk]==0 or self.thread.desknostate[tmpdesk]==2):
                        self.desk = tmpdesk
                        self.scene = self.thread.desknomap[tmpdesk]
                        if (self.thread.desknostate[tmpdesk]==0):
                            self.thread.desknostate[tmpdesk]=1
                        elif (self.thread.desknostate[tmpdesk]==2):
                            self.thread.desknostate[tmpdesk]=3
                        break
                else:
                    if (self.thread.desknostate[tmpdesk]==1 or self.thread.desknostate[tmpdesk]==0):
                        self.desk = tmpdesk
                        self.scene = self.thread.desknomap[tmpdesk]
                        if (self.thread.desknostate[tmpdesk]==0):
                            self.thread.desknostate[tmpdesk]=2
                        elif (self.thread.desknostate[tmpdesk]==1):
                            self.thread.desknostate[tmpdesk]=3
                        break
                               
            
        self.sit_down(self.scene, self.desk)
        self.stream.set_iq_set_handler("query","jabber:moblove:appointment:inviting",self.inviting_iq)        
        self.stream.set_iq_set_handler("query","jabber:moblove:appointment:inviting",self.inviting_iq)
        
    def notauthorized(self):
        self.logon_ui.logic_logon_failed()        

    def sit_down(self, scene, desk=None, nearby=None):
        iq = iq_sit_down(self, scene, desk, nearby)        
        iq.send_iq()

    def get_all_scene_user_list(self):
        iq = iq_get_all_scene_users(self)
        iq.send_iq()
        
    def inviting_iq(self, iq):
        user_nodes=iq.xpath_eval("g:query/g:user",{"g":"jabber:moblove:appointment:inviting"})
        for xmlnode in user_nodes:
            userjid = str(xmlnode.prop("jid"))
            break
        iq=iq.make_result_response()
        iq.new_query("jabber:moblove:appointment:inviting")        
        self.stream.send(iq)
        
#        agreeiq = Iq(to_jid=JID("appointment."+self.jid.domain), stanza_type="set")
#        q = agreeiq.new_query("jabber:moblove:appointment:refuse")
#        q.newChild(q.ns(), "jid", userjid)
#        self.stream.send(agreeiq)
                

    def disconnected(self):
        self.logic_ui.hide(self)
        self.thread.user_disconnected(self)

    def idle(self):
        SimpleClient.idle(self)
        if self.session_established:
            target=JID("jajcus",self.jid.domain)
            self.stream.send(Message(to_jid=target,body=unicode("Teścik","utf-8")))        
#        if (time.time()-self.lasttime > 60):
#            self.lasttime = time.time()
#            iq = iq_get_scene_users(self)
#            iq.send_iq()
        

    def post_disconnect(self):
        print "Disconnected"
        raise Disconnected


def test():
    logger=logging.getLogger()
    logger.addHandler(logging.StreamHandler())
    logger.setLevel(logging.DEBUG)
    
    libxml2.debugMemory(1)
    
    print "creating stream..."
    s=MyClient(jid=JID("1324374623@mk/win32"),password=u"abcdefg",auth_methods=["sasl:DIGEST-MD5","digest"],
               server="127.0.0.1", port=5222)
    
    print "connecting..."
    s.connect()
    
    print "processing..."
    try:
        try:
            s.loop(1)
        finally:
            s.disconnect()
    except KeyboardInterrupt:
        traceback.print_exc(file=sys.stderr)
    except (StreamError,Disconnected),e:
        raise
    
    libxml2.cleanupParser()
    if libxml2.debugMemory(1) == 0:
        print "OK"
    else:
        print "Memory leak %d bytes" % (libxml2.debugMemory(1))
        libxml2.dumpMemory()
    # vi: sts=4 et sw=4    

